#!/bin/bash
# puppet        Init script for running the puppet client daemon
#
# Author:       Duane Griffin <d.griffin@psenterprise.com>
#               David Lutterkort <dlutter@redhat.com>
#
# chkconfig: - 98 02
#
# description: Enables periodic system configuration checks through puppet.
# processname: puppet
# config: /etc/sysconfig/puppet

# Source function library.
. /etc/rc.d/init.d/functions

PATH=/opt/puppetlabs/puppet/bin:/usr/bin:/sbin:/bin:/usr/sbin
export PATH

[ -f /etc/sysconfig/puppet ] && . /etc/sysconfig/puppet
lockfile=/var/lock/subsys/puppet
pidfile=/var/run/puppetlabs/agent.pid
puppetd=/opt/puppetlabs/puppet/bin/puppet
RETVAL=0

PUPPET_OPTS="agent "

# Determine if we can use the -p option to daemon, killproc, and status.
# RHEL < 5 can't.
if status | grep -q -- '-p' 2>/dev/null; then
    daemonopts="--pidfile $pidfile"
    pidopts="-p $pidfile"
fi

# Figure out if the system just booted. Let's assume
# boot doesn't take longer than 5 minutes
## Not used for now
##[ -n "$INIT_VERSION" ] && PUPPET_OPTS="${PUPPET_OPTS} --fullrun"

start() {
    echo -n $"Starting puppet agent: "
    daemon $daemonopts $puppetd ${PUPPET_OPTS} ${PUPPET_EXTRA_OPTS}
    RETVAL=$?
    echo
        [ $RETVAL = 0 ] && touch ${lockfile}
        return $RETVAL
}

stop() {
    echo -n $"Stopping puppet agent: "
    killproc $pidopts $puppetd
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

reload() {
    echo -n $"Restarting puppet agent: "
    killproc $pidopts $puppetd -HUP
    RETVAL=$?
    echo
    return $RETVAL
}

restart() {
    stop
    start
}

rh_status() {
    status $pidopts $puppetd
    RETVAL=$?
    return $RETVAL
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

genconfig() {
    echo -n $"Generate puppet agent configuration: "
    $puppetd ${PUPPET_OPTS} ${PUPPET_EXTRA_OPTS} --genconfig
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        restart
    ;;
    reload|force-reload)
        reload
    ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
    ;;
    status)
        rh_status
    ;;
    once)
        shift
        $puppetd ${PUPPET_OPTS} --onetime ${PUPPET_EXTRA_OPTS} $@
        ;;
    genconfig)
        genconfig
    ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload|force-reload|condrestart|once|genconfig}"
        exit 1
esac

exit $RETVAL
